// 首页组件
// 展示应用的主页面，包含用户登录、搜索、推荐内容等功能
import './Home.css' // 首页样式
import Recommend from '../components/Recommend' // 推荐组件
// import UserAvatar from '@/components/UserAvatar' // 用户头像组件（已注释）
import React, { useState, useEffect } from 'react'; // React hooks
import WeChatLoginModal from '@/components/WeChatLoginModal' // 微信登录弹窗
import Header from '@/components/Header/Header' // 页面头部组件
import Startcreate from '@/components/Startcreate/Startcreate'; // 开始创建组件

// 全局类型声明：侧边栏折叠状态
declare global {
  interface Window {
    __SIDEBAR_COLLAPSED__?: boolean; // 侧边栏是否折叠
  }
}

const Home = () => {
  // 用户菜单显示状态
  const [showUserMenu, setShowUserMenu] = useState(false) // 控制用户下拉菜单显示
  const [isLoggedIn, setIsLoggedIn] = useState(false) // 控制登录状态
  const [showStickySearch, setShowStickySearch] = useState(false); // 控制粘性搜索栏显示

  // 登录弹窗显示状态
  const [showLogin, setShowLogin] = useState(true)

  // 监听滚动事件，控制粘性搜索栏的显示
  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 220) {
        setShowStickySearch(true); // 滚动超过220px时显示粘性搜索
      } else {
        setShowStickySearch(false); // 否则隐藏
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll); // 清理事件监听
  }, []);

  // 处理登出逻辑
  const handleLogout = () => {
    // 清除本地存储的用户信息
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    // 设置登录状态为false，显示登录注册按钮
    setIsLoggedIn(false)
    setShowUserMenu(false)
  }

  // 处理登录按钮点击
  const handleLogin = () => {
    setShowLogin(true)
    // 不要在这里 setIsLoggedIn(true)
  }

  // 模拟用户信息数据
  const userInfo = {
    name: '小鲨鱼', // 用户姓名
    role: '创建者', // 用户角色
    userId: '107944274', // 用户ID
    avatar: 'KTV', // 头像文字
    membership: '免费版', // 会员类型
    storage: { used: '0K', total: '3G' }, // 存储使用情况
    aiStickers: 100 // AI贴纸数量
  }

  // 处理登录成功回调
  const handleLoginSuccess = () => {
    setIsLoggedIn(true)
    setShowLogin(false)
  }

  // 获取侧边栏折叠状态
  // 假设你有isCollapsed状态从MainLayout传递或用context管理
  // 这里以window全局变量模拟（实际应用可用context或props传递）
  const isSidebarCollapsed = window.__SIDEBAR_COLLAPSED__ || false;
  
  // 根据侧边栏状态添加对应的CSS类
  useEffect(() => {
    if (isSidebarCollapsed) {
      document.body.classList.add('sidebar-collapsed');
      document.body.classList.remove('sidebar-expanded');
    } else {
      document.body.classList.add('sidebar-expanded');
      document.body.classList.remove('sidebar-collapsed');
    }
  }, [isSidebarCollapsed]);

  // 首页标签页配置
  const tabs = [
    '海报', '小红书', 'PPT办公', '公众号', '电商', '教育培训', '社交生活', '个性定制', '印刷物料'
  ];

  // 各标签页对应的数据
  const tabData = {
    '海报': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '手机海报' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '全屏海报' },
      { img: 'https://img.shetu66.com/2023/04/25/1682391094827084.png', text: '长图海报' },
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '横版海报' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '方形海报' },
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '每日一签' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: 'AI招聘海报' },
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: 'AI海报' },
    ],
    '小红书': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '小红书封面' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '小红书笔记' },
    ],
    'PPT办公': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: 'PPT模板' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '办公文档' },
    ],
    '公众号': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '公众号封面' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '推文配图' },
    ],
    '电商': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '电商主图' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '电商详情' },
    ],
    '教育培训': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '教育海报' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '培训讲义' },
    ],
    '社交生活': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '社交配图' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '生活记录' },
    ],
    '个性定制': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '定制名片' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '定制礼品' },
    ],
    '印刷物料': [
      { img: 'https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg', text: '宣传单' },
      { img: 'https://img95.699pic.com/photo/40244/2615.jpg_wh860.jpg', text: '折页' },
    ],
  };

  // 当前激活的标签页
  const [activeTab, setActiveTab] = useState('海报');

  return (
    <div className="home-page">
      {/* 微信登录弹窗 */}
      <WeChatLoginModal
        open={showLogin}
        onClose={() => setShowLogin(false)}
        onLoginSuccess={handleLoginSuccess}
      />

      {/* 内容主体 */}
      <div className="content-body">
        {/* 用户头部区域 */}
        <div className="user-header">
          {/* 粘性搜索栏：滚动时显示 */}
          {showStickySearch && (
            <div className="sticky-search-inner">
              <span className="search-icon-v2">
                <svg width="20" height="20" viewBox="0 0 22 22" fill="none"><circle cx="10" cy="10" r="7" stroke="#bfc8d7" strokeWidth="2"/><path cx="16" cy="16" d="M16 16l4 4" stroke="#bfc8d7" strokeWidth="2" strokeLinecap="round"/></svg>
              </span>
              <input
                className="sticky-search-input"
                placeholder="输入关键词搜索你想要的模板或素材"
              />
              <button className="search-btn-v2">搜索</button>
            </div>
          )}
          {isLoggedIn ? (
            <div 
              className="user-avatar"
              onMouseEnter={() => setShowUserMenu(true)}
            >
              <div className="avatar-circle">
                <span className="avatar-text">{userInfo.avatar}</span>
              </div>
              
              {/* 用户信息下拉菜单 */}
              {showUserMenu && (
                <div 
                  className="user-menu"
                  onMouseEnter={() => setShowUserMenu(true)}
                  onMouseLeave={() => setShowUserMenu(false)}
                >
                  {/* 用户信息区域 */}
                  <div className="user-info-section">
                    <div className="user-avatar-large">
                      <span className="avatar-text">{userInfo.avatar}</span>
                    </div>
                    <div className="user-details">
                      <div className="user-name">
                        {userInfo.name}
                        <span className="user-role">{userInfo.role}</span>
                      </div>
                      <div className="user-id">
                        用户ID: {userInfo.userId}
                        <button className="copy-btn">📋</button>
                      </div>
                    </div>
                  </div>

                  {/* 会员推广区域 */}
                  <div className="membership-section">
                    <div className="membership-content">
                      <div className="membership-header">
                        <span className="membership-icon">V</span>
                        <span className="membership-title">{userInfo.membership}</span>
                      </div>
                      <div className="membership-desc">开通会员尊享专属特权</div>
                      <div className="membership-benefits">50万+模板·商用授权·无水印下载</div>
                    </div>
                    <button className="upgrade-btn">立即开通</button>
                  </div>

                  {/* 功能使用情况 */}
                  <div className="usage-section">
                    <div className="usage-cards">
                      <div className="usage-card">
                        <div className="usage-title">
                          存储空间
                          <span>扩容 {'>'}</span>
                        </div>
                        <div className="usage-progress">
                          <div className="progress-bar">
                            <div className="progress-fill" style={{ width: '0%' }}></div>
                          </div>
                        </div>
                        <div className="usage-text">{userInfo.storage.used} / {userInfo.storage.total}</div>
                      </div>

                      <div className="usage-card">
                        <div className="usage-title">
                          AI贴贴
                          <span>加购 {'>'}</span>
                        </div>
                        <div className="ai-stickers">
                          <span className="sticker-count">{userInfo.aiStickers}</span>
                        </div>
                        <div className="sticker-desc">
                          <span>会员每月免费领贴贴</span>
                          <span>{'>'}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* 账户管理 */}
                  <div className="account-section">
                    <div className="account-header">
                      <div className="free-trial-badge">免费体验</div>
                      <div className="account-user">
                        <div className="account-avatar">
                          <span className="avatar-text">{userInfo.avatar}</span>
                        </div>
                        <div className="account-name-container">
                          <span className="account-name-main">{userInfo.name}.</span>
                          <span className="account-name-sub">个人版</span>
                        </div>
                      </div>
                      <span className="create-team-btn">+ 创建团队</span>
                    </div>
                    
                    <div className="account-menu">
                      <div className="menu-item">
                        <span className="menu-icon">⚙️</span>
                        <span className="menu-text">团队管理</span>
                      </div>
                      <div className="menu-item">
                        <span className="menu-icon">📄</span>
                        <span className="menu-text">订单/发票</span>
                      </div>
                      <div className="menu-item">
                        <span className="menu-icon">💬</span>
                        <span className="menu-text">消息中心</span>
                      </div>
                      <div className="menu-item">
                        <span className="menu-icon">🎫</span>
                        <span className="menu-text">我的优惠券</span>
                      </div>
                    </div>
                  </div>

                  {/* 退出登录按钮 */}
                  <button className="logout-btn" onClick={handleLogout}>
                    退出登录
                  </button>
                </div>
              )}
            </div>
          ) : (
            // 未登录时显示登录按钮
            <div className="auth-buttons">
              <button className="login-btn" onClick={handleLogin}>
                登录
              </button>
            </div>
          )}
        </div>
        
        {/* 用户头部占位符 */}
        <div className="user-header-placeholder"></div>
   
        {/* 页面头部：非粘性搜索时显示 */}
        {!showStickySearch && (
          <Header></Header>
        )}

      <Startcreate></Startcreate>
      <div className="content-body">
        <Recommend />
     
      </div>
    </div>
    </div>
  )
}

export default Home
